import { reqCartList,reqDeleteCartById,reqUpdateCheckedById} from "@/api"
const state = {
    cartList:[]
}
const mutations = {
    GETCARTLIST(state, cartList) {
        state.cartList = cartList
    }
}
const actions = {
  async  getCartList({commit}){
       let result= await reqCartList();
       console.log(result);
       if(result.code==200){
           commit("GETCARTLIST",result.data)
       }
    },
    //删除购物车某一个产品
    async deleteCartListById({commit},skuId){
        let result=await reqDeleteCartById(skuId);
        if(result.code==200){
            return "ok"
        }else{
            return Promise.reject(new Error('faile'))
        }
    },
    //修改某一个产品的状态
    async updateCheckedById({commit}, {skuId, isChecked}){
      //此处ischecked修改不了实际商品点击的状态，只是修改了vuex中的状态
        let result=await reqUpdateCheckedById(skuId,isChecked);
        if(result.code==200){
            return "ok"
        }else{
            return Promise.reject(new Error('faile'))
        }
    },
    //删除全部选中的产品
    //需要调用多次deleteCartListById
    deleteAllCheckedCart({dispatch,getters}){
        //获取购物车中全部的产品
        let promiseAll=[]
        getters.cartInfoList.forEach(item=>{
            let promise=dispatch("deleteCartListById",item.skuId);
            //将每一次返回的promise添加到数组中
            promiseAll.push(promise)
        })
        //只要有一个失败，则返回一个失败的promise
        //只要全部成功，则返回一个成功的promise
        
        return Promise.all(promiseAll)
    },
    //修改全部产品的状态
    updateAllCartIsChecked({dispatch,state},isChecked){
         let promiseAll=[];
         
         state.cartList[0].cartInfoList.forEach(item=>{
             let promise=dispatch("updateCheckedById",{skuId:item.skuId,isChecked})
             promiseAll.push(promise)
         })
         return Promise.all(promiseAll)
    }
}
const getters = {
    cartList(state){
        return state.cartList[0]||{}
    },
    cartInfoList(state){
        //购物车中选中的商品
        return state.cartList[0] ? state.cartList[0].cartInfoList.filter(item=>item.isChecked==1) : []
    }
}
export default {
    
    state,
    mutations,
    actions,
    getters
}